// console.log(document.cookie); // 获取浏览器的cookie
//设置cookie
function setCookie(name, value) {
    document.cookie = name + "=" + escape(value) + "; path=/";
}

//时间格式化
// new Date().Format("yyyyMMddhhmmssS")
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//获取cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

// 读取本地存储数据
function getData() {
    var data = localStorage.getItem("yxxq");
    if (data !== null) {
        return JSON.parse(data);
    } else {
        return [];
    }
}

// 保存本地数据到 localStorage
function saveData(data) {
    localStorage.setItem("yxxq", JSON.stringify(data));
}

// JSON.parse, JSON.stringify

var myName = "";
var myID = "";
var myVersion = "202012181445"
var myyxIndex = -1;
// 浙江省市级 静态 已定
var zjxzqy1 = [{"浙江省行政区": ["杭州市", "宁波市", "温州市", "嘉兴市", "湖州市", "绍兴市", "金华市", "衢州市", "舟山市", "台州市", "丽水市"]}];

var zjxzqy2 = {
    "zjxzq": [
        {
            "id": "杭州市",
            "country": ["上城区", "下城区", "江干区", "拱墅区", "西湖区", "滨江区", "萧山区", "余杭区", "富阳市", "临安市", "建德市", "桐庐县", "淳安县"]
        },
        {"id": "宁波市", "country": ["海曙区", "江北区", "北仑区", "镇海区", "鄞州区", "奉化区", "象山县", "宁海县", "余姚市", "慈溪市"]},
        {"id": "温州市", "country": ["鹿城区", "龙湾区", "瓯海区", "洞头区", "永嘉县", "平阳县", "苍南县", "文成县", "泰顺县", "瑞安市", "乐清市"]},
        {"id": "嘉兴市", "country": ["南湖区", "秀洲区", "嘉善县", "海盐县", "海宁市", "平湖市", "桐乡市"]},
        {"id": "湖州市", "country": ["吴兴区", "南浔区", "德清县", "长兴县", "安吉县"]},
        {"id": "绍兴市", "country": ["越城区", "柯桥区", "上虞区", "新昌县", "诸暨市", "嵊州市"]},
        {"id": "金华市", "country": ["婺城区", "金东区", "武义县", "浦江县", "磐安县", "兰溪市", "义乌市", "东阳市", "永康市"]},
        {"id": "衢州市", "country": ["柯城区", "衢江区", "常山县", "开化县", "龙游县", "江山市"]},
        {"id": "舟山市", "country": ["定海区", "普陀区", "岱山县", "嵊泗县"]},
        {"id": "台州市", "country": ["椒江区", "黄岩区", "路桥区", "三门县", "天台县", "仙居县", "玉环市", "温岭市", "临海市"]},
        {"id": "丽水市", "country": ["莲都区", "青田县", "缙云县", "遂昌县", "松阳县", "云和县", "庆元县", "景宁畲族自治县", "龙泉市"]}
    ]
};

///
layui.use(['layer', 'form', 'table', 'element', 'jquery', 'slider', 'treeTable'], function () {

    var layer = layui.layer;
    var element = layui.element;
    var form = layui.form;
    var $ = layui.jquery;
    var slider = layui.slider;
    var table = layui.table;
    var treeTable = layui.treeTable;
    var picihao1 = 0;
    var hideBtn = $('#hideBtn');
    var exportTable=null;
    //专题分景的数据
    var ztfenjngData=null;
    //影像合并的数据
    var yxunionData=null;
    //基础分景的数据处理
    var jcfenjingData=null;

    var rightHide = $('#hide-right');
    var rightLayout = $('#rightLayout');
    var leftHide = $('#hide-left');
    var leftLayout = $('#leftLayout');

    var mainLayout = $('#main-layout');
    var mainMask = $('.main-mask');
    var rectangular = $('#rectangular');
    rectangular.on('click', () => {
        ClearDraw();
        DrawRec(2)
    })
    var polygon = $('#polygon');
    polygon.on('click', () => {
        ClearDraw();
        DrawRec(1);
    })

    //开启范围选择
    slider.render({
        elem: '#slideTest9',
        value: [0, 30], //初始值
        range: true, //范围选择
        theme: '#788ea8',
        change: function (vals) {
            //  $('#test-slider-tips2').html('开始值：'+ vals[0] + '、结尾值：'+ vals[1]);
            var rangeLeft = $('#sliderInput_1').val(vals[0] + '%');
            var rangeRight = $('#sliderInput_2').val(vals[1] + '%');
        }
    });
    //动态绑定批次号的值
    $.ajax({
        url: baseurl + '/fetchPicihao',
        method: 'POST',
        contentType: false,
        success: function (res) {
            console.log(res);//下面会提到这个res是什么值
            //使用循环遍历，给下拉列表赋值
            $.each(res.data, function (index, value) {
                // console.log(value.department_id);
                $('#dp').append(new Option(value));// 下拉菜单里添加元素
            });
            layui.form.render("select");//重新渲染 固定写法
            //动态绑定景号

        }
    })
    //监听导航点击
    element.on('nav(leftNav)', function (elem) {
        var navA = $(elem).find('a');
        var id = navA.attr('data-id');
        var url = navA.attr('data-url');
        var text = navA.attr('data-text');
        if (!url) {
            return;
        }
        var isActive = $('.main-layout-tab .layui-tab-title').find("li[lay-id=" + id + "]");
        if (isActive.length > 0) {
            //切换到选项卡
            element.tabChange('tab', id);
        } else {
            element.tabAdd('tab', {
                title: text,
                content: '<iframe src="' + url + '" name="iframe' + id + '" class="iframe" framborder="0" data-id="' + id +
                    '" scrolling="auto" width="100%"  height="100%"></iframe>',
                id: id
            });
            element.tabChange('tab', id);

        }
        mainLayout.removeClass('hide-side');
    });
    //批次号下拉框数据更新
    form.on('select(pch)', function (data) {
        picihao1 = data.value;
    });
    //分景按照影像查询
    $('#fenjingquery').on('click', function () {
        $.ajax({
            url: baseurl + 'fetchImageByPicihao?picihao=' + picihao1 + '&size=10',
            method: 'POST',
            dataType: 'JSON',
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                jcfenjingData=res.data;
                for(var i in jcfenjingData){
                    jcfenjingData[i].status="未处理";
                }
                if (res.code >= 0) {
                    table.reload('table_1', {
                        data: jcfenjingData
                    })
                    $.each(res.data, function (index, value) {
                        // console.log(value.department_id);
                        $('#jh').append(new Option(value.filename));// 下拉菜单里添加元素
                        // console.log("查到的数据"+value.filename)
                    });
                    layui.form.render("select");//重新渲染 固定写法
                }
            }
        });
    });
    //监听导航点击
    element.on('nav(rightNav)', function (elem) {
        var navA = $(elem).find('a');
        var id = navA.attr('data-id');
        var url = navA.attr('data-url');
        var text = navA.attr('data-text');
        if (!url) {
            return;
        }
        var isActive = $('.main-layout-tab .layui-tab-title').find("li[lay-id=" + id + "]");
        if (isActive.length > 0) {
            //切换到选项卡
            element.tabChange('tab', id);
        } else {
            element.tabAdd('tab', {
                title: text,
                content: '<iframe src="' + url + '" name="iframe' + id + '" class="iframe" framborder="0" data-id="' + id +
                    '" scrolling="auto" width="100%"  height="100%"></iframe>',
                id: id
            });
            element.tabChange('tab', id);

        }
        mainLayout.removeClass('hide-side');
    });
    //菜单隐藏显示
    hideBtn.on('click', function () {
        if (!rightHide.hasClass('hide-side')) {
            mainLayout.addClass('hide-side');
        } else {
            mainLayout.removeClass('hide-side');
        }
    });
    //右侧边栏隐藏
    rightHide.on('click', function () {
        if (!rightLayout.hasClass('hide')) {
            rightLayout.addClass('hide');
            if (leftLayout.hasClass('hide')) {
                $('#map').css("width", "100%");
            } else {
                $('#map').css("width", "86%");
            }
            map.updateSize();//刷新openlayer地图容器大小
        } else {
            rightLayout.removeClass('hide');
            if (leftLayout.hasClass('hide')) {
                $('#map').css("width", "71%");
            } else {
                $('#map').css("width", "57%");
            }
            map.updateSize();
        }
    })

    //左侧边栏隐藏
    leftHide.on('click', function () {
        if (!leftLayout.hasClass('hide')) {
            leftLayout.addClass('hide');
            $('#map').css("margin-left", "0");
            if (rightLayout.hasClass('hide')) {
                $('#map').css("width", "100%");
                map.updateSize();
            } else {
                $('#map').css("width", "71%");
                map.updateSize();
            }
        } else {
            leftLayout.removeClass('hide');
            $('#map').css("margin-left", "220px");
            if (rightLayout.hasClass('hide')) {
                $('#map').css("width", "86%");
                map.updateSize();
            } else {
                $('#map').css("width", "57%");
                map.updateSize();
            }
        }
    })
    //遮罩点击隐藏
    mainMask.on('click', function () {
        mainLayout.removeClass('hide-side');
    })

    //监听影像详情: iframe.html
    $(document).on('click', '.detail_icon', function (obj) {
        // 获取当前点击的影像信息
        console.log('影像id: ', table.cache["data-table"][myyxIndex].id);
        saveData(table.cache["data-table"][myyxIndex]);
        //调整眼睛的图片

        // 打开影像详情页面
        layer.open({
            title: '影像详情',
            type: 2,
            area: ['900px', '510px'],
            offset: '50px',
            resizing: false,
            content: 'iframe.html',
            scrollbar: false,
        })
        light(lightimgarr);
        return false;
    });
    //监听高亮————有问题
    $(document).on('mouseenter', '.layui-table>tbody>tr', function () {
        myyxIndex = $(this).data('index');
        // 获取当前影像名
        // const yxname = table.cache["data-table"][myyxIndex].imageName;
        // console.log(yxname);
        //Highlight(yxname);
        /* if (index % 2 == 0) {
            Highlight('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216')
        } else {
            Highlight('GF1_WFV4_E120.5_N26.8_20140929_L1A0000364925')
        } */
        return false;
    })

    //监听眼睛变化
    $(document).on('click', '.eye', function () {
        // 获取当前影像名
        const yxname = table.cache["data-table"][myyxIndex].imageName;
        console.log('地图上显示影像名: ', yxname);

        if ($(this).hasClass('eye-on')) {
            $(this).removeClass('eye-on')
            $(this).attr('src', 'img/eye.png')
        } else {
            $(this).addClass('eye-on')
            $(this).attr('src', 'img/eye-light.png')
            displayImg(yxname);
        }
        return false;
    });

    // 监听退出
    $('#login_status').on('click', function () {
        layer.confirm('确认要退出吗？', {
            icon: 3,
            title: '系统提示',
            btn: ['确定', '取消']//按钮
        }, function (index) {

            layer.close(index);
            //此处请求后台程序，下方是成功后的前台处理……

            console.log('要退出登录吗！');
            $("#login_status").hide();
            // cookie 置空
            setCookie("name", "");
            setCookie("useid", "");

            window.location.href = "";
            console.log('删除');

        });
        /*
                layui.layer.open({
                    type: 1,
                    title: false,
                    area: ['400px', '285px'],
                    offset: '50px',
                    resizing: false,
                    content: $('.login-window'),
                    scrollbar: false,
                    closeBtn: 0
                }); */
        return false;
    })

    /*	//监听影像入库菜单
        $('#input').on('click', function () {
            // 点击菜单 “影像入库”
            var today = new Date();
            var year = today.getFullYear();
            var month = today.getMonth() + 1;
            var date = today.getDate();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
            var orderDate = year + '-' + month + "-" + date;
            $('.batch').children().text(orderDate)
            layer.open({
                title: '影像入库',
                type: 1,
                area: ['400px', '240px'],
                offset: '50px',
                resizing: false,
                content: $('.input-window'),
                scrollbar: false,
            })
            return false;
        })*/
    //监听影像入库菜单
    $('#input').on('click', function () {
        // 点击菜单 “影像入库”
        var orderDate = new Date().Format("yyyyMMddhhmmssS");
        $('.batch').children().text(orderDate)
        layer.open({
            title: '影像入库',
            type: 1,
            area: ['400px', '240px'],
            offset: '50px',
            resizing: false,
            content: $('.input-window'),
            scrollbar: false,
        })
        return false;
    })
    //监听基础分景处理
    $('#handle1').on('click', function () {

        layer.open({
            type: 1,
            title: '基础分景处理',
            area: ['1700px', '620px'],
            shift: 1,
            shift: 1,
            resizing: false,
            content: $('#handle_table1'),
            scrollbar: false,
            closeBtn: 2,
        })
        return false;

    })
    //监听分景处理复选框
    form.on('checkbox(imageProduct)', function (data) {
        if (data.value != 'on') {
            $('.productId').prop('checked', false)
        } else {
            var items = $('.productId').map((index, val) => {
                return val
            }).toArray()
            let arr = []
            items.forEach((item, index) => {
                if (item.checked) {
                    arr.push(index)
                }
            })
            for (let i = 0; i < arr[arr.length - 1]; i++) {
                items[i].checked = true
            }
        }

        form.render('checkbox')

        // item.each(function(index,value){
        // 	if($(this).prop('checked')){
        // 		console.log(index)
        // 		for(let i = 0;i<index;i++){
        // 			item[i].setAttribute('checked','checked')
        // 		}
        // 		form.render('checkbox')
        // 	}
        // })
    })
    //监听专题分景处理
    $('#handle2').on('click', function () {
        layer.open({
            type: 1,
            title: '专题分景处理',
            area: ['1200px', '620px'],
            shift: 1,
            offset: '50px',
            resizing: false,
            content: $('#handle_table2'),
            scrollbar: false,
            closeBtn: 2
        })
        return false;
    })

    //实现用户和注册功能
    $('#login').on('click', function () {
        layer.open({
            type: 1,
            title: false,
            area: ['400px', '285px'],
            offset: '50px',
            resizing: false,
            content: $('.login-window'),
            scrollbar: false,
            closeBtn: 0
        })
        return false;
    })

    // yxmerger
    /*影像合并的之前的代码备份
    *  var selectData = layui.table.checkStatus('data-table').data;//demo是table的id
        console.log('合并selected', selectData);

        let param = {
            "current": 0,
            "ids": "1",
            "names": "GF1_PMS1_E120.5_N30.5_20131118_L1A0000112691-PAN1",
            "size": 0
        }
        console.log('I need to datebase', param);
        layer.load(2);
        $.ajax({
            url: baseurl + 'queryByIdName',
            data: param,
            method: 'POST',
            dataType: 'JSON',
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                console.log('发送请求了')

            },
            error: function (xhr) {
                console.log(`错误状态${xhr.status}，错误${xhr.statusText}`)
            },
            complete: function () {
                layer.closeAll();
            }
        })

        return false;
    *
    *
    * */
    $('#yxmerger').on('click', function () {
        layer.open({
            type: 1,
            title: '合并影像操作',
            area: ['1100px', '660px'],
            shift: 1,
            offset: '50px',
            resizing: false,
            content: $('#yxmerger_table2'),
            scrollbar: false,
            closeBtn: 2
        })
        return false;
    })

    //影像导出表格的结果输出
    $('#yxexport').on('click', function () {
        var selectData = layui.table.checkStatus('data-table').data;//demo是table的id
        console.log('导出selected', selectData);
        var arrays=new Array();
        for(var i in selectData){
            var target={
            'filename': selectData[i].filename,
            'satellitenameen':selectData[i].satellitenameen,
            'sensorName': selectData[i].sensorName,
            'acquisitionTime':selectData[i].acquisitionTime,
            'cloudPercent': selectData[i].cloudPercent
            }
            arrays.push(target);
        }
        table.exportFile(['文件名','卫星','传感器','采集时间','云量'], arrays, 'csv');
        return false;
    })
    let renderCover = function (result) {
        treeTable.render({
            elem: '#coverratetable',
            data: result,
            tree: {
                iconIndex: 0,           // 折叠图标显示在第几列
                isPidData: true,        // 是否是id、pid形式数据
                idName: 'id',  // id字段名称
                pidName: 'pid'     // pid字段名称
            },
            cols: [[
                {field: 'name', width: 140, title: '卫星', unresize: true},
                {field: 'coverrate', width: 94, title: '覆盖率(%)', unresize: true},
                {field: 'scenecount', width: 60, title: '景数(景)', unresize: true},
                {field: 'export', width: 93, title: '导出', templet: '#barDemo', unresize: true}
            ]]
        });
    }
    let initData = []
    //renderCover(initData)


    let trans = function (obj) {
        var tableData = ['a', 'b', 'c', 'd', 'e']
        let res = []
        var temp = {}
        temp.name = obj.name
        temp.coverrate = obj.coverrate.toFixed(2)
        temp.scenecount = obj.scenccount
        temp.pid = 0
        temp.id = 'A'
        temp = {}
        for (let i = 0; i < obj.List.length; i++) {
            temp.name = obj.List[i].name
            temp.coverrate = obj.List[i].coverrate.toFixed(2)
            temp.scenecount = obj.List[i].scenecount
            temp.id = tableData[i], temp.pid = 'A', res.push(temp), temp = {}
            let arr = obj.List[i].List
            for (let j = 0; j < arr.length; j++) {
                temp.name = arr[j].name
                temp.coverrate = arr[j].coverrate.toFixed(2)
                temp.scenecount = arr[j].scenecount
                temp.pid = tableData[i]
                temp.id = j + 1 + i * 100
                res.push(temp)
                temp = {}
            }
        }
        return res
    }
    let coverData = {
        name: "整体覆盖",
        coverrate: 0.8367396675017937,
        scenccount: 2,
        List: [
            {
                name: "亚米",
                coverrate: 0.8367396675017937,
                scenecount: 2,
                List: [
                    {
                        name: "GF1",
                        coverrate: 0.8367396675017937,
                        scenecount: 2
                    }
                ]
            }
        ]
    }
    console.log(trans(coverData))
    renderCover(trans(coverData))
    // 影像覆盖率计算
    $('#yxCoverage').on('click', function () {

        var selectData = layui.table.checkStatus('data-table').data;//demo是table的id

        if (JSON.stringify(selectData) !== "") {
            let datas = [""];
            let i = 0;
            for (var data1 in selectData) {
                var imageName = selectData[data1]["imageName"];
                datas[i++] = imageName.replaceAll(" ", "_");
            }
            var city = $("#select_city").find("option:selected").text();
            var selectedCountry = $("#select_country").val();
            let strXZQHLayerNameCN = "地市";
            if (selectedCountry.endsWith("县") || selectedCountry.endsWith("区")) {
                strXZQHLayerNameCN = "县";
            }
            var strImageNames = datas.join(",");
            var formData = new FormData();
            formData.append("strImageNames", strImageNames);
            formData.append("strXZName", city);
            formData.append("strXZQHLayerNameCN", strXZQHLayerNameCN);
            //加载过渡动画
            var loading = layer.load(2);

            //请求覆盖率计算
            $.ajax({
                url: baseurl + 'ComputeCoverAreaAPI',
                data: formData,
                method: 'POST',
                processData: false,
                contentType: false,
                success: function (res) {
                    console.log("success request", res);

                    /*
                    * {
                            "name": "整体覆盖",
                            "coverrate": 0.8367396675017937,
                            "scenccount": 2,
                            "List": [
                                {
                                    "name": "亚米",
                                    "coverrate": 0.8367396675017937,
                                    "scenecount": 2,
                                    "List": [
                                        {
                                            "name": "GF1",
                                            "coverrate": 0.8367396675017937,
                                            "scenecount": 2
                                        }
                                    ]
                                }
                            ]
                        }
                    * */
                    /*
                    * {
                          "code": 0,
                          "message": "成功500:所有结合表中没有指定影像的记录!",
                          "count": null,
                          "data": "11"
                      }
                    *
                    * */

                    /*
                    * {
                          "timestamp": "2021-01-11T14:02:04.054+00:00",
                          "status": 500,
                          "error": "Internal Server Error",
                          "message": "",
                          "path": "/ComputeCoverAreaAPI"
}
                    *
                    * */
                    if (res.code >= 0) {
                        if (res["name"] === "null") {
                            if (res["code"] === "null") {
                                layer.error("计算出现异常");
                            } else {
                                layer.error(res["message"]);
                            }
                        } else {
                            $("#coveratetag").append("<p>" + res["name"] + "</p>");
                            $("#coveratetag").append("<p>" + res["coverrate"] + "</p>");
                        }
                        let tmpData = $.parseJSON(res.message.substring(2));


                        renderCover()
                        $("#coverateTab").addClass("layui-this");
                        $("#queryResultTab").removeClass("layui-this");
                        $("#queryResultTabContent").removeClass("layui-show");
                        $("#coverateTabContent").addClass("layui-show");

                    } else {
                        layer.msg('计算覆盖率出现错误')
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    /*错误信息处理*/
                    // alert("进入error---");
                    // alert("状态码："+xhr.status);
                    // alert("状态:"+xhr.readyState);//当前状态,0-未初始化，1-正在载入，2-已经载入，3-数据进行交互，4-完成。
                    // alert("错误信息:"+xhr.statusText );
                    layer.msg('计算覆盖率出现错误');
                    console.log("返回响应信息：" + xhr.responseText);//这里是详细的信息
                },
                complete: function () {
                    layer.close(loading);
                }
            })
        } else {
            layer.msg("请先选择影像，然后进行覆盖率计算");
        }
    });
    // 影像数据入库接口
    $('#toData').on('click', function () {
        const path = $('#yxroad').val();
        const url = encodeURI(baseurl + 'fileAdd?filePath=' + path + '&userId=' + parseInt(myID) + '&picihao=' + new Date().Format("yyyyMMddhhmmss"));
        console.log('I need to datebase', url);
        var loading = layer.load(2);
        $.ajax({
            url: url,
            type: 'POST',
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                console.log('收到响应返回', res);
                if (res.code === 0) {
                    // 清空入库路径
                    document.getElementById("yxroad").value = "";
                    layer.closeAll();
                } else {
                    layer.msg('影像入库出错!');
                }
            },
            error: function (xhr) {
                console.log(`错误状态${xhr.status}，错误${xhr.statusText}`)
            },
            complete: function () {
                layer.close(loading)
            }
        })

        return false;
    })

    $('#register').on('click', function () {
        window.location.href = "register.html";
        return false;
    })
    $('#btn-login').on('click', function () {
        window.location.href = "index.html";
        return false;
    })
    $('.login-footer-register').on('click', function () {
        window.location.href = "register.html";
        return false;
    })

    $(document).on('click', '#data-table', function () {
        console.log('main.js: 太急了jjj');
        return false;
    })


    // select的change事件
    form.on('select(test-city)', function (data) {
        //TODO执行自己的代码
        const cityn = $("#select_city").val();// 值
        const city = $("#select_city").find("option:selected").text();// 文本内容
        // console.log(zjxzqy2['zjxzq'][0].country);
        console.log('select1 change...' + city);

        // 地图联动
        loadBoundary(1, city);

        // 初始化选中的地级市的县和区
        $("#select_country").empty();
        $("#select_country").append("<option value=''>请选择县/区</option>");
        //console.log(zjxzqy2['zjxzq'][cityn].country);
        for (let index in zjxzqy2['zjxzq'][cityn].country) {
            // console.log(zjxzqy2['zjxzq'][cityn].country[index]);
            var item = zjxzqy2['zjxzq'][cityn].country[index];
            $("#select_country").append("<option value='" + item + "'>" + item + "</option>");
        }
        form.render();
    });

    form.on('select(test-country)', function (data) {
        //TODO执行自己的代码
        const country = $("#select_country").val();
        console.log('select2 change...' + country);
        loadBoundary(2, country);
    });


    // 登录
    form.on('submit(login-form)', function (data) {
        //layer.msg('登录中...')
        layer.load(2);
        data.field.status = 1;
        data.field.phone = '13713577906';
        let param = data.field;
        console.log(param)
        $.ajax({
            url: baseurl + 'user/login',
            data: JSON.stringify(param),
            method: 'POST',
            dataType: 'JSON',
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                console.log("success request", res);
                if (res.code >= 0) {
                    const user = JSON.parse(res.data);
                    console.log('登录的用户信息', user);
                    setTimeout(() => {
                        layer.msg('登录成功!')
                        myID = user.userid;
                        myName = user.username;
                        console.log("login done，myName：" + myName + "," + myID);
                        $("#login_status").text(myName + '|退出登录');
                        setCookie("name", myName);
                        setCookie("useid", myID);
                        $("#login_status").show();
                        // 重置清空
                        document.getElementById("logname").value = "";
                        document.getElementById("logpasswd").value = "";
                        layer.closeAll();
                        form.render();//必须写
                    }, 1000)
                } else {
                    layer.msg('用户名或密码错误！')
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                layer.msg('登录失败!');
                console.log("返回响应信息：" + xhr.responseText);//这里是详细的信息
            },
            complete: function () {
                layer.close(index);
            }
        })
        var index = layer.load(1, {
            shade: [0.1, '#fff'] //0.1透明度的白色背景
        });
        return false;
    });
    // jquery 入口及登录，判断是否有 cookie
    $(document).ready(function () {

        $("#login_status").hide();
        /* console.log(zjxzqy2['zjxzq'][0].country);
        for(let key  in zjxzqy2){
            for(let key1 in zjxzqy2[key]){
                for(let key2 in zjxzqy2[key][key1])
            console.log(key + '---' + key1+ '---' + key2+ '---' + zjxzqy2[key][key1][key2])
            }
      } */

        // 获取当前 html 文件
        var strUrl = window.location.href;
        var arrUrl = strUrl.split("/");
        var strPage = arrUrl[arrUrl.length - 1];
        //alert(strPage);
        if (strPage != 'register.html') {
            console.log(document.cookie); // 获取浏览器的cookie
            myName = getCookie('name') || "";
            myID = getCookie('useid') || "";
            console.log('I am coming...，myName：' + myName + ', myID: ' + myID);// myVersion
            if (myName === '') {
                $("#login_status").hide();
                layui.layer.open({
                    type: 1,
                    title: false,
                    area: ['400px', '285px'],
                    offset: '50px',
                    resizing: false,
                    content: $('.login-window'),
                    scrollbar: false,
                    closeBtn: 0
                });
            } else {
                $("#login_status").text(myName + '|退出登录');
                console.log("cookie, are you ok, " + myName + "," + myID);
                $("#login_status").show();
            }
        }
    })
    // 注册
    form.on('submit(register)', function (data) {
        if (data.field.password != data.field.confirm) {
            layer.msg('两次密码不相符，请重新填写！');
            return false;
        } else {
            delete data.field.confirm
            data.field.status = 0
        }
        let param = data.field;
        console.log(param)
        $.ajax({
            url: baseurl + 'user/register',
            data: JSON.stringify(param),
            method: 'POST',
            dataType: 'JSON',
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                console.log('发送请求了')
                if (res.code >= 0) {
                    layer.msg('注册成功！')
                } else {
                    layer.msg(res.message)
                }
            },
            error: function (xhr) {
                console.log(`错误状态${xhr.status}，错误${xhr.statusText}`)
            },
            complete: function () {
            }
        })
        return false;
    })

    //监听影像查询条件，进行查询
    form.on('submit(query)', function (data) {
        // loadBoundary(1,'杭州市')
        console.log("选中的查询数据：", data.field)
        let time = [];
        let cloud = []
        time[0] = data.field.dateStart + ' 00:00:00';
        time[1] = data.field.dateEnd + ' 00:00:00';

        cloud[0] = data.field.cloudOne
        cloud[1] = data.field.cloudTwo
        let sensor = []
        let tmp = data.field
        delete tmp.dateStart
        delete tmp.dateEnd
        delete tmp.cloudOne
        delete tmp.cloudTwo
        let obj = tmp;
        let arr = Object.getOwnPropertyNames(obj)
        for (let i = 0; i < arr.length; i++) {
            var arrays = arr[i].split("$");
            let resolutionId = parseFloat(arrays[0]);
            let imageType = arrays[1];
            let satellite = arrays[2];
            let objTmp = {
                resolutionId,
                satellite,
                imageType
            }
            sensor.push(objTmp)
        }
        let param = {
            /*	cloudBegin: parseInt(cloud[0]),
                cloudEnd: parseInt(cloud[1]),*/
            current: 1,
            sensor: sensor,
            size: 10,
            /*		timeBegin: time[0],
                    timeEnd: time[1]*/
        }
        console.log("影像查询数据：", param);
        var loading = layer.load(2);

        $.ajax({
            url: baseurl + 'query',//'http://118.178.140.168:8888/map/data/layers/demo.json', // 别忘记改回去 baseurl + 'query',
            data: JSON.stringify(param),
            method: 'POST',
            dataType: 'JSON',
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                console.log('查询返回：', res)
                if (res.code >= 0) {
                    let yxs = res.data;
                    ztfenjngData=res.data;
                    //专题分景数据绑定列
                    for(var i in ztfenjngData){
                        ztfenjngData[i].status="未处理";
                    }

                    //影像合并的状态列绑定
                    for(var i in yxunionData){
                        yxunionData[i].status="未处理";
                    }
                    yxunionData=res.data;
                    // 表格重载数据
                    table.reload('data-table', {
                        data: res.data
                    })
                    //影像合并
                    table.reload('data-table1', {
                        data: res.data
                    })
                    table.reload('table_2', {
                        data: ztfenjngData
                    })
                    $("#imageMergerTip").css("display", "none");
                    console.log('查询成功!', yxs)
                    // 影像属性查询结果是否为0
                    if (yxs.length > 0) {
                        // 空间查询 arr: 影像名称数组，way: 1
                        var arrayObj = new Array();　//创建一个数组
                        yxs.forEach(function (value, i) {
                            console.log('forEach遍历:' + i + '--' + value.imageName);
                            arrayObj.push(value.imageName)
                        })
                        console.log('空间查询', arrayObj);
                        var result = query(arrayObj, 1);
                        console.log('空间查询结果', result)
                        if (!result || result.length === 0) {
                            console.log('空间查询失败')
                        } else {
                            // 再次查询，然后表格加载数据
                            var strR = result.toString();
                            console.log('空间查询结果', strR);
                            let param = {
                                //ids: "28,29",
                                names: strR
                            };
                            console.log(param)
                            $.ajax({
                                url: baseurl + 'queryByIdName',
                                data: JSON.stringify(param),
                                method: 'POST',
                                dataType: 'JSON',
                                contentType: "application/json;charset=utf-8",
                                success: function (res) {
                                    console.log("success request", res);
                                    if (res.code >= 0) {
                                        const obj = JSON.parse(res.data);
                                        console.log('登录的用户信息', obj);
                                        setTimeout(() => {
                                            layer.msg('登录成功!');
                                            $("#imageMergerTip").css("display", "none");
                                            // 表格重载数据
                                            table.reload('data-table', {
                                                data: res.data
                                            });
                                            table.reload('data-table1', {
                                                data: res.data
                                            });
                                            table.reload('table_2', {
                                                data: res.data
                                            });
                                        }, 1000)
                                    } else {
                                        layer.msg('影像查询失败！');
                                        $("#imageMergerTip").css("display", "block");
                                    }
                                },
                                error: function (xhr, textStatus, errorThrown) {
                                    layer.msg('影像查询失败！!');
                                    console.log("返回响应信息：" + xhr.responseText);//这里是详细的信息
                                    $("#imageMergerTip").css("display", "block");
                                },
                                complete: function () {
                                    console.log("关闭第二次请求");
                                }
                            })
                        }
                        $("#queryTab").removeClass("layui-this");
                        $("#queryResultTab").addClass("layui-this");
                        $("#queryTabContent").removeClass("layui-show");
                        $("#queryResultTabContent").addClass("layui-show");
                    } else {
                        layer.msg("查找不到符合条件的影像数据!")
                    }
                } else {
                    layer.msg(res.message)
                }
            },
            error: function (xhr) {
                console.log(`错误状态${xhr.status}，错误${xhr.statusText}`)
            },
            complete: function () {
                layer.close(loading);
                console.log("关闭影像查询请求");
            }
        })
        return false
    })

    form.verify({
        username: function (value, item) {
            if (value == '') {
                return '用户名不能为空'
            }
            if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                return '用户名不能有特殊字符';
            }
            if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                return '用户名首尾不能出现下划线\'_\'';
            }
            if (/^\d+\d+\d$/.test(value)) {
                return '用户名不能全为数字';
            }
        }
        , phone: [
            /^1\d{10}$/,
            "请输入正确的手机号",
        ]

        , password: [
            /^[\S]{6,12}$/
            , '密码必须6到12位，且不能出现空格'
        ]
    });
    //基础分景处理
    table.on('checkbox(table_1)', function(obj){
        console.log(obj.checked); //当前是否选中状态
        console.log(obj.data); //选中行的相关数据
        console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
        console.log(); // 获取表格中选中行的数据
    });
    form.on('select(iamgeType)', function (data) {
        let id = data.elem.dataset.value; //当前数据的id
        let valueTmp = data.elem.value; //当前字段变化的值
        jcfenjingData[id].imageType=valueTmp;
    });
    form.on('select(spotType)', function (data) {
        let id = data.elem.dataset.value; //当前数据的id
        let valueTmp = data.elem.value; //当前字段变化的值
        jcfenjingData[id].spotparam=valueTmp;
    });
    //基础风景处理
    $("#fenjingsubmit").click(function(){
        layer.msg("开始分景处理");

        //进行分景处理
        var loading = layer.load(2);
        for(var i in table.checkStatus('table_1').data){
            for(var j in  jcfenjingData){

                if(jcfenjingData[j].filename ===table.checkStatus('table_1').data[i].filename){

                    table.checkStatus('table_1').data[i].imageType=jcfenjingData[j].imageType;
                    table.checkStatus('table_1').data[i].spotparam=jcfenjingData[j].spotparam;
                    console.log(table.checkStatus('table_1').data[i].imageType+"----------"+jcfenjingData[j].imageType);
                    break;
                }
            }
            if(table.checkStatus('table_1').data[i].imageType === undefined){
                table.checkStatus('table_1').data[i].imageType="辐射定标";
            }
            if(table.checkStatus('table_1').data[i].spotparam === undefined ){
                table.checkStatus('table_1').data[i].spotparam="其他";
            }
            console.log("正在处理的"+table.checkStatus('table_1').data[i].imageType);
            var tx=f(table.checkStatus('table_1').data[i].imageType);
            layer.msg("开始处理"+table.checkStatus('table_1').data[i].filename);
            var url1=encodeURI(baseurl + 'ScenceOperation?strRSProducts=' + tx + '&strVectorProducts=' + table.checkStatus('table_1').data[i].spotparam + '&userId=' + parseInt(myID)+"&strImageId="+table.checkStatus('table_1').data[i].id);
            $.ajax({
                url:url1,
                method: 'POST',
                dataType: 'JSON',
                contentType: 'application/json;charset=utf-8',
                success: function (res) {
                    if (res.code >= 0) {
                        layer.msg('分景'+table.checkStatus('table_1').data[i].filename+"处理成功")
                    } else {
                        layer.msg(res.message)
                    }
                },
                error: function (xhr) {
                    console.log(`错误状态${xhr.status}，错误${xhr.statusText}`)
                }
            })
        }
        layer.close(loading);
    });

    //图像产品设计的参数配置

function f(str) {
    var tx="";
    switch (str) {
        case "影像融合":
            tx="影像融合,地形校正,正射纠正,大气校正,辐射定标";
            break;
        case "地形校正":
            tx="地形校正,正射纠正,大气校正,辐射定标";
            break;
        case "正射纠正":
            tx="正射纠正,大气校正,辐射定标";
            break;
        case "大气校正":
            tx="大气校正,辐射定标";
            break;
        default:
            tx="辐射定标";
    }
  return tx;
}
   
	//合并结合表
	var lngUnionJHBID = 3
	form.on('submit(unionJHBbtn)',function(mergeData){
		console.log('合并结合表')
		let checkStatus = table.checkStatus('data-table1')
		let data = checkStatus.data
		var strImageNames = data.map((value)=>{
			return value.imageName
		}).join(',')
		console.log(strImageNames)
		let blnYL = mergeData.field.isInclude == '包含'?true:false
		$.post(baseurl + '/CreateUnionJHB',{
			strImageNames,
			blnYL
		},function(res){
			console.log(res)
			if(res.code == 0){
				layer.msg(res.data,{
					time:1200
				})
				$("#unionspotbtn").removeAttr("disabled");
			}else {
				layer.msg('请求失败',{
					time:1200
				})
			}
		})
		
	})
	
	//合并图斑unionspotbtn
	form.on('submit(unionspotbtn)',function(mergeData){
		console.log('合并图斑')
		var city = $("#select_city").find("option:selected").text();
		var selectedCountry = $("#select_country").val();
		let strXZQHLayerNameCN = "地市";
		if (selectedCountry.endsWith("县") || selectedCountry.endsWith("区")) {
		    strXZQHLayerNameCN = "县";
		}
		let strXZName = selectedCountry
		let typeArr = []
		let typeName = ['云量','植被','建筑','水体','其他']
		for(key in mergeData.field){
			if(key.substring(0,5) == 'spot-'){
				typeArr.push(typeName[key.substring(key.length-1)])
			}
		}
		let strSpotTypeCNs = typeArr.join(',')
		$.post(baseurl + '/CreateUnionSpot',{
			lngUnionJHBID,
			strSpotTypeCNs,
			strXZQHLayerNameCN,
			strXZName
		},function(res){
			if(res.code == 0){
				layer.msg(res.data,{
					time:1200
				})
			}else {
				layer.msg('请求失败',{
					time:1200
				})
			}
		})
	})
});
